<template>
  <div>
    <el-button type="success" @click="env_edit = true">创建</el-button>
    <el-input v-show="sinput" v-model="search" :suffix-icon="Search" class="table_search" placeholder="搜索"/>
  </div>
  <Table v-model:data="tableData" style="width: 100%" @submit="CreateEnv">
    <el-table-column prop="name" label="环境名" width="180"/>
    <el-table-column prop="utime" label="修改时间" width="180"/>
    <el-table-column prop="Owner.username" label="所属人" width="180"/>
    <el-table-column prop="Project.name" label="所属项目" width="180"/>
    <el-table-column prop="desc" label="状态" />
    <el-table-column fixed="right" label="操作" width="180px">
      <template #default="scope">
        <el-button color="#C4C3C2" size="small" @click="GetEnvInfo">
          <el-icon>
            <el-tooltip content="环境信息">
              <View/>
            </el-tooltip>
            </el-icon>
        </el-button>

        <el-button  color="#EA9D2BC4" size="small"  @click="OpenNodeInfo(scope.row)"><el-icon><Edit /></el-icon></el-button>
        <el-button  color="#E3262FD9" size="small"  @click="OpenNodeInfo(scope.row)"><el-icon><Delete /></el-icon></el-button>
      </template>
    </el-table-column>
  </Table>
  <Pagination @change="ListEnv" v-model:page="page"/>


  <el-drawer v-model="table" title="环境信息" direction="rtl" size="50%">
    <el-table :data="gridData.nodes">
      <el-table-column label="IP" prop="ip"/>
    </el-table>

    <el-table :data="gridData.param_list" @expand-change="onExpand" :border=false
              :header-cell-style="{background:'rgba(91,165,225,0.9) none repeat scroll 0% 0%',color:'rgb(33, 27, 38)','font-family':'Open Sans'}">
      <el-table-column label="参数名" prop="k">
        <template #default="p">
          <el-input v-model="p.row.k" class="kv"></el-input>
        </template>

      </el-table-column>
      <el-table-column label="值" prop="v">
        <template #default="p">
          <el-input v-model="p.row.v"></el-input>
        </template>
      </el-table-column>
    </el-table>
  </el-drawer>

  <el-drawer v-model="env_edit" :title=env_edit_title direction="rtl" size="70%">
    <el-form :model="form" label-width="80px">
      <el-form-item label="环境名称">
        <el-input v-model="form.name" style="width: 240px"/>
      </el-form-item>

      <el-form-item label="所属项目">
        <el-input v-model="project.name" disabled style="width: 240px"/>
      </el-form-item>

      <el-button type="success" @click="AddNode">增加节点</el-button>
      <el-form-item>
        <el-container>
          <el-aside width="200px">
            <ul>
              <li v-for="node in form.nodes" @click="SwitchNode(node)" :class="{ active: node.isActive }">{{ node.ip }}
                <el-icon class="node-minus" @click="RemoveNode(node)">
                  <Minus/>
                </el-icon>
              </li>
            </ul>
          </el-aside>
          <el-main>
            <template v-if="form.nodes.length != 0">
              <el-table :data="cur_node.param" @expand-change="onExpand" border
                        :header-cell-style="{background:'rgba(253, 253, 253, 0.9) none repeat scroll 0% 0%',color:'rgb(33, 27, 38)','font-family':'Open Sans'}">
                <el-table-column label="参数名" prop="k">
                  <template #default="p">
                    <el-input v-model="p.row.k" class="kv"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="值" prop="v">
                  <template #default="p">
                    <el-input v-model="p.row.v" class="kv"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="标签" prop="v">
                  <template #default="p">
                    <el-input v-model="p.row.v" class="kv"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作"/>
              </el-table>
              <el-divider>
                <el-button @click="AddRow" plain link>
                  <el-icon>
                    <Plus/>
                  </el-icon>
                </el-button>
              </el-divider>
            </template>

          </el-main>
        </el-container>
      </el-form-item>
    </el-form>

    <Table :data="param" :stripe="false">
      <el-table-column label="参数名" prop="k">
        <template #default="p">
          <el-input v-model="p.row.k" class="kv"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="值" prop="v">
        <template #default="p">
          <el-input v-model="p.row.v" class="kv"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作"/>
    </Table>
    <el-divider>
      <el-button @click="AddFormParam" plain link>
        <el-icon>
          <Plus/>
        </el-icon>
      </el-button>
    </el-divider>
    <template #footer>
      <el-button type="success" @click="OnSubmit">提交</el-button>
    </template>

    <el-drawer v-model="add_node" title="添加节点" direction="rtl" size="35%">
      <Table v-model:data="Nodes" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="ip" label="IP地址" width="180">
          <template #default="scope">
            <span id="ip">{{ scope.row.ip }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Owner.username" label="Owner" width="180"/>
      </Table>
      <Pagination @change="ListNode" v-model:page="page"/>
      <template #footer>
        <el-button type="success" @click="SubAddNode">确认</el-button>
      </template>
    </el-drawer>
  </el-drawer>
</template>

<script lang="ts" setup>
import {env} from './env_api'
import {node} from './node_api'
import {user} from '../user/user_api.js'
import {Search} from '@element-plus/icons-vue'
import {onMounted, reactive, ref} from 'vue'
import Pagination from '@/components/common/Pagination.vue'
import Table from '@/components/common/Table.vue'

import {ElMessage, ElMessageBox} from 'element-plus'

let page = reactive({page: 1, size: 15, total: 0})
var dialogVisible = ref(false)
const Nodes = ref([])
const add_node = ref(false)
const search = ref("")
const tableData = ref([])
const table = ref(false)
const env_edit = ref(false)
const env_edit_title = ref("创建环境")
const gridData = ref([])
const project = ref({name:""})
const cur_node = ref({})
import {useUserStore} from '@/pinia/modules/user'

const store = useUserStore()

const form = ref({
  name: "",
  nodes: [],
  param: {},
  project:"",
})

const param = ref([])
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const OnSubmit = async () => {
  var new_form = form.value
  new_form.param = {}
  for (var i in param.value) {
    var value = param.value[i]
    var k = value['k']
    var v = value['v']
    if (k in new_form.param) {
      ElMessage.error("参数" + k + "重复")
      return
    }
    new_form.param[k] = v
  }

  var new_nodes = []
  var nodes = new_form.nodes
  for (var i in nodes) {
    var node = nodes[i]

    var node_param = {}
    var old_node_param = node.param
    for (var i in old_node_param) {
      if (old_node_param[i].k in param) {
        ElMessage.error("参数" + old_node_param[i].k + "重复")
        return
      }else{
        node_param[old_node_param[i].k] = old_node_param[i].v
      }
    }
    new_nodes.push({
      id: node.id,
      param: node_param
    })
  }
  if (env_edit_title.value == "修改环境") {
    await env.Modify({id:form.value.id,project:form.value.project,name: form.value.name, nodes: new_nodes, params: new_form.param})
  }else{
    await env.Create({name: form.value.name,project:form.value.project, nodes: new_nodes, params: new_form.param})
  }

  ListEnv()
  dialogVisible.value = false
}
const SubAddNode = () => {
  if (multipleSelection.value.length == 0) {
    return
  }
  for (var i in multipleSelection.value) {
    var node = multipleSelection.value[i]
    if (!form.value.nodes.includes(node)) {
      form.value.nodes.push({ip: node.ip, id: node.id, param: []})
    }
  }
  cur_node.value = form.value.nodes[0]
  cur_node.value.isActive = true
  add_node.value = false
}

onMounted(async () => {
  ListEnv()
  ListNode()
  project.value = await store.GetProject()
  form.value.project = project.value.id
})

const ListNode = async () => {
  var res = await node.List({query: {"all": true}})
  Nodes.value = res.data
  dialogVisible.value = true
}

const ListProject = async () => {
  const store = useUserStore()
  const username = store.GetUserInfo()
  var res = await user.Project(username)
}

const EnvInfo = async (name) => {
  ListProject()
  var res = await env.Detail(name)
  for (var i in res.nodes) {
    res.nodes[i].param = []
    if (res.node_params != null){
      if (res.node_params.hasOwnProperty(res.nodes[i].id)) {
        for (var k in res.node_params[res.nodes[i].id]){
          res.nodes[i].param.push({"k":k,"v":res.node_params[res.nodes[i].id][k]})
        }
      }
    }else{
      res.nodes[i].param = []
    }
  }
  for (var k in res.params) {
    param.value.push({"k":k,"v":res.params[k]})
  }
  form.value = res
  form.value.project = res.Project.name
}


const AddNode = () => {
  add_node.value = true
}

const ListEnv = async () => {
  var res = await env.List(page)
  tableData.value = res.data
  page.total = res.total
}

const CreateEnv = async () => {
  var res = await node.List(page)
  Nodes.value = res.data
  env_edit.value = true
  ListProject()
}

const OpenNodeInfo = async (row) => {
  row.param_list = []
  env_edit_title.value = "修改环境"
  await EnvInfo(row.name)

  cur_node.value = form.value.nodes[0]
  cur_node.value.isActive = true
  env_edit.value = true
}
const AddRow = () => {
  if (cur_node.value.param == undefined) {
    cur_node.value.param = []
  }
  cur_node.value.param.push({"k": ""})
}

const AddFormParam = () => {
  param.value.push({'k': ""})
}

// 展开事件触发
function onExpand(row, expandedRows) {
  // 判断当前展开行
  console.log(row, ":asdf")
}


const SwitchNode = (node) => {
  var param = {}
  cur_node.value.isActive = false
  var old_param = cur_node.value.param
  if (cur_node.value.param == undefined) {
    cur_node.value.param = [{"k": ""}]
  }
  for (var i in old_param) {
    if (old_param[i].k in param) {
      ElMessage.error("参数" + old_param[i].k + "重复")
      return
    }else{
      if (old_param[i].k.length != 0) {
        param[old_param[i].k] = old_param[i].v
      }

    }
  }
  cur_node.value = node
  cur_node.value.isActive = true
}
const RemoveNode = (node) => {
  ElMessageBox.confirm('确认要移除节点' + node.ip + "吗？", '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    form.value.nodes = form.value.nodes.filter(function (v, i, arr) {
          return v != node
        })
        ElMessage({
          type: 'info',
          message: `移除成功`,
        })
      })
}

const GetEnvInfo = ()=>{

}
</script>

<style scoped>
@import "@/styles/table_common.scss";

:deep(.el-drawer__header) {
  margin: 0 !important;
  background-color: #00ff80;
}

.kv :deep( .el-input__wrapper) {
  border: none !important;
  box-shadow: none !important;

  padding: 0 10px
}

:deep(.el-form-item__content) {
  margin: 0 !important;
}

.el-aside {
  max-height: 300px;
  height: 300px;
  width: 140px;
  overflow: auto;
}

li {
  margin-top: 6px;
  margin-right: 20px;
  font-size: 14px;
  padding: 3px 10px;
}

li:hover {
  background-color: gainsboro;
  .node-minus {
    display: inline;
    float: right;
    padding-top: 10px;
  }
}

.node-minus {
  display: none;
  padding-top: 10px;
  color: #a89b0d;
}
.active {
  border-bottom: #a4751e solid; /* 添加下划线效果 */
  border-width: 4px; /* 设置下划线的粗细为2像素 */
}
:deep(.el-drawer__title){
  color: black;
  font-family: 黑体;
  font-weight: bold;
}
</style>
